package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.apis.article.IArticleClient;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.model.admin.dtos.NewsAuthDto;
import com.heima.model.admin.vos.NewsAuthVo;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WemediaClientService;
import io.netty.util.concurrent.PromiseAggregator;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.admin.KafkaAdminClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class WemediaClientServiceImpl implements WemediaClientService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private IArticleClient iArticleClient;
    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;


    /**
     * 查询列表封装数据
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult newListVo(NewsAuthDto dto) {
        //校验参数
        if (dto.getPage() == null) {
            dto.setPage(1);
        }
        if (dto.getSize() == null) {
            dto.setSize(10);
        }
        //分页查询文章信息及用户名字

        Integer page = (dto.getPage() - 1) * dto.getSize();
        String title = dto.getTitle();
        if (title != null) {
            title = "%" + title + "%";
        }

        List<WmNews> list = wmNewsMapper.pageWmNewsAndUserName(dto.getStatus(), title, page, dto.getSize());

//        //分页参数
//        IPage<WmNews> page = new Page(dto.getPage(), dto.getSize());
//        LambdaQueryWrapper<WmNews> lqw = new LambdaQueryWrapper<>();
//        lqw.like(dto.getTitle() != null, WmNews::getTitle, dto.getTitle());
//        lqw.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
//        lqw.orderByDesc(WmNews::getSubmitedTime);
//        //查询分页
//        page = wmNewsMapper.selectPage(page, lqw);
//
//        List<WmNews> records = page.getRecords();
//        //判空
//        if (records == null) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
//        }
//        List<NewsAuthVo> newsAuthVos = new ArrayList<>();
//        //封装参数
//        for (WmNews record : records) {
//            NewsAuthVo newsAuthVo = new NewsAuthVo();
//            if (record != null) {
//                BeanUtils.copyProperties(record, newsAuthVo);
//                WmUser wmUser = wmUserMapper.selectById(record.getUserId());
//                if (wmUser != null) {
//                    newsAuthVo.setAuthorName(wmUser.getName());
//                    newsAuthVos.add(newsAuthVo);
//                }
//            }
//        }
//        log.info("获取到的集合为：{}，集合长度为：{}", newsAuthVos, newsAuthVos.size());
//        ResponseResult responseResult = new PageResponseResult(dto.getPage(),
//                dto.getSize(), Math.toIntExact(page.getTotal()));
//        responseResult.setData(newsAuthVos);

        log.info("获取到的分页数据为：{}",list.toString());
        PageResponseResult pageResponseResult = new PageResponseResult(page, dto.getSize(), -1);
        pageResponseResult.ok(list);
        return pageResponseResult;
    }

    /**
     * 查询单个文章详情
     *
     * @param wmNewsId
     * @return
     */
    @Override
    public ResponseResult oneVoById(Integer wmNewsId) {
        if (wmNewsId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = wmNewsMapper.selectById(wmNewsId);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        NewsAuthVo newsAuthVo = new NewsAuthVo();
        BeanUtils.copyProperties(wmNews, newsAuthVo);
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        newsAuthVo.setAuthorName(wmUser.getName());

        return ResponseResult.okResult(newsAuthVo);
    }

    /**
     * 成功审核
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authPass(NewsAuthDto dto) {
        //根据id查询文章
        WmNews wmNews = wmNewsMapper.selectById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (wmNews.getStatus() != WmNews.Status.ADMIN_AUTH.getCode()) {
            //不为人工审核状态
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);

        }
        //人工审核通过 发布
        //调用参数
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        ResponseResult responseResult = saveAppArticle(wmNews);

        if (responseResult == null || !responseResult.getCode().equals(200)) {
            throw new RuntimeException("WmNewsAutoScanServiceImpl-保存app端的文章失败");
        }
        wmNews.setArticleId((Long) responseResult.getData());
        wmNewsMapper.updateById(wmNews);
        // 发送信息，生成静态页面
        Map<String, Object> map = new HashMap<>();
        map.put("articleId", wmNews.getArticleId() + "");
        kafkaTemplate.send(WmNewsMessageConstants.ARTICLE_STATIC_URL_CREATE_TOPIC, JSON.toJSONString(map));
        
        return responseResult.ok(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 审核成功保存App端数据
     *
     * @param wmNews
     * @return
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
        //调用app端
        ArticleDto dto = new ArticleDto();
        //属性拷贝
        BeanUtils.copyProperties(wmNews, dto);

        //布局
        dto.setLayout(wmNews.getType());

        //频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }
        //作者
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null) {
            dto.setAuthorId(wmUser.getId().longValue());
            dto.setAuthorName(wmUser.getName());
        }

        //文章(ap_article)id
        if (wmNews.getArticleId() != null) {
            dto.setId(wmNews.getArticleId());
        }

        //创建时间
        dto.setCreatedTime(new Date());

        //发送请求，远程调用
        return iArticleClient.saveAppArticle(dto);
    }

    /**
     * 失败审核
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authFail(NewsAuthDto dto) {
        WmNews wmNews = wmNewsMapper.selectById(dto.getId());
        if (wmNews == null && wmNews.getStatus() != WmNews.Status.ADMIN_AUTH.getCode()) {
            //不为人工审核状态
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        wmNews.setStatus(WmNews.Status.FAIL.getCode());
        if (dto.getMsg() != null) {
            wmNews.setReason(dto.getMsg());
        }

        wmNewsMapper.updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
